import {useRef, useEffect, useState, RefObject} from 'react'
import { Modal, Form, FormInstance, Select, Input, Switch, AutoComplete, Row, Col, message } from 'antd';
import { ServiceSchema, ServiceTopicSchema } from '@src/components/schema/service'
import {awaitWrap, emailPattern} from '@js/tool'
import { PartySchema } from '@src/components/schema/caseSchema'
import { EAddressSchema } from '@src/components/schema/address'
import {getAddressListRequest, getContentRequest, addModalRequest, updateModalRequest} from './ajax'
import { CaseSchema } from '@components/schema/caseSchema';
import { ArbitratorSchema } from '@components/schema/arbitrator';
import moment, { Moment } from 'moment'
import _ from 'lodash'
import Text from '@components/text'
import Upload, { uploadFile } from '@components/upload'

const {Item} = Form
const {Option} = Select
const {TextArea} = Input
const partTypes = ['申请人', '申请人代理人', '被申请人', '被申请人代理人']
const shortLabel = { span: 6 }
const longLabel = { span: 3 }
const longWrap = { span: 20 }

async function initAddressList (caseid: string, setList: (v: EAddressSchema[]) => void) {
  const [e, d] = await awaitWrap(getAddressListRequest(caseid))
  if (e === null && d !== null) {
    setList(d)
  }
}

async function initContent (formRef: RefObject<FormInstance>, caseid: string, topicType: string, addressId: string) {
  const h = message.loading('加载内容中', 120)
  const [e, d] = await awaitWrap(getContentRequest(caseid, topicType, addressId))
  h()
  const c = formRef.current
  if (e === null && d !== null && c !== null) {
    const documentid = (d.documents || []).map(li => li.id)
    delete d.documents
    d.documentid = documentid
    c.setFieldsValue(d)
  }
}

// 改变主体类型
function changeSubject (
  e: string,
  d: CaseSchema | null,
  arbitrators: ArbitratorSchema[],
  formRef: RefObject<FormInstance>,
  setContractList: (v: PartySchema[]) => void,
  setType: (v: string) => void
) {
  if (d === null) {
    return undefined
  }
  let list: PartySchema[] = []
  switch (e) {
    case '申请人':
      list = d.applicants.filter(li => li.status)
      break
    case '被申请人':
      list = d.respondents.filter(li => li.status)
      break
    case '申请人代理人':
      list = d.applicant_agents
      break
    case '被申请人代理人':
      list = d.respondents_agents
      break
    case '仲裁员':
      list = arbitrators as unknown as PartySchema[]
      break
    default:
      list = []
      break
  }
  setContractList(list)
  setType(e)
  formRef.current?.setFieldsValue({
    action_subject: e
  })
}

function changeContractId (
  id: string,
  list: PartySchema[],
  formRef: RefObject<FormInstance>,
  type: string,
  allAddressList: EAddressSchema[],
  setAddressList: (v: EAddressSchema[]) => void
) {
  let obj = null
  // c.resetFields()
  const c = formRef.current
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      obj = list[i]
      break
    }
  }
  c?.setFieldsValue({
    action_subject: type,
    contract_type: obj ? obj.subject_type : '',
    contract: obj && obj.name !== '其他' ? obj.name : '',
    contractid: id,
  })
  const currentAddressList = allAddressList.filter(li => li.contractid === id && li.status === 1).map((li, i) => {
    li.value = `${li.mobile}${i}`
    li.label = `${(i + 1)}、${li.mobile || '无手机号'}`
    return li
  })
  setAddressList(currentAddressList)
}

function changeAddress (formRef: RefObject<FormInstance>, o: EAddressSchema, caseid: string, topic: ServiceTopicSchema) {
  initContent(formRef, caseid, topic.type, o.id)
  formRef.current?.setFieldsValue({
    contract: o.contract || undefined,
    addressid: o.id || undefined,
    type: o.type || undefined,
    zip_code: o.zip_code || undefined,
    structure: o.structure || undefined,
    mobile: o.mobile || undefined,
    tel: o.tel || undefined,
    tel_office: o.tel_office || undefined,
    address: o.address || undefined,
    email: o.email || undefined
  })
}

async function sumbmitHandle (d: {[k: string]:any}, caseDetail: CaseSchema, theme: ServiceTopicSchema, refreshFn: () => void, hide: () => void) {
  // d.islast_known_place = d.islast_known_place ? 1 : 0
  let requestFn = addModalRequest
  if (d.id) {
    requestFn = updateModalRequest
  }
  if (d.file instanceof Array && d.file.length > 0) {
    const files = await uploadFile(d.file)
    d.fileid = files.map(li => li.id).join()
    delete d.file
  }
  const h = message.loading('提交中', 120)
  d.to_type = '电子送达'
  d.caseid = caseDetail.id
  d.topicid = theme.id
  d.topic_name = theme.name
  if (d.send_datetime instanceof moment) {
    d.send_datetime = Math.floor((d.send_datetime as Moment).valueOf() / 1000)
  }
  if (d.arrive_datetime instanceof moment) {
    d.arrive_datetime = Math.floor((d.arrive_datetime as Moment).valueOf() / 1000)
    if (d.status === undefined) {
      d.status = '送达'
    }
  }
  const [e] = await awaitWrap(requestFn(d))
  h()
  if (e === null) {
    hide()
    refreshFn()
  }
}

// 初始化数据
function initDefaultData (
  formRef: RefObject<FormInstance>,
  data: ServiceSchema,
  caseDetail: CaseSchema,
  arbitrators: ArbitratorSchema[],
  setContractList: (v: PartySchema[]) => void,
  setType: (v: string) => void
) {
  const c = formRef.current
  const d: {[k: string]: any} = _.cloneDeep(data)
  if (!c) {
    return undefined
  }
  changeSubject(d.action_subject, caseDetail, arbitrators, formRef, setContractList, setType)
  if (d.id) {
    if (d.send_datetime) {
      d.send_datetime = moment(d.send_datetime * 1000)
    } else {
      d.send_datetime = undefined
    }
    if (d.arrive_datetime) {
      d.arrive_datetime = moment(d.arrive_datetime * 1000)
    } else {
      d.arrive_datetime = undefined
    }
  }
  if (d.file instanceof Array) {
    d.file.forEach(li => {
      li.name = li.original_filename
    })
  }
  d.islast_known_place = d.islast_known_place === 1
  c.setFieldsValue(d)
}

function fillEmpty (v?: string | number) {
  if (v === undefined || v === null || v === '') {
    return '无'
  }
  return `${v}`
}

interface Props {
  caseid: string
  caseDetail: CaseSchema | null
  visible: boolean
  data: ServiceSchema | null
  arbitrators: ArbitratorSchema[]
  topic: ServiceTopicSchema | null
  hide: () => void
  refreshFn: () => void
}

function Main ({caseid, visible, caseDetail, arbitrators, data, topic, hide, refreshFn}: Props) {
  const formRef = useRef<FormInstance>(null)
  const [contractList, setContractList] = useState<PartySchema[]>([])
  const [addressList, setAddressList] = useState<EAddressSchema[]>([])
  const [allAddressList, setAllAddressList] = useState<EAddressSchema[]>([])
  const [type, setType] = useState('')
  useEffect(() => {
    if (visible) {
      const h = message.loading('加载中', 120)
      Promise.all([initAddressList(caseid, setAllAddressList)])
        .then(() => { h()}, () => { h()})
      if (data && caseDetail) {
        initDefaultData(formRef, data, caseDetail, arbitrators, setContractList, setType)
      }
    } else {
      if (formRef.current) {
        formRef.current.resetFields()
      }
    }
  }, [visible])
  return (
    <div>
      <Modal title={data ? '修改送达信息' : '新增送达信息'} width={800} visible={visible} onCancel={() => hide()} onOk={() => formRef.current?.submit()} >
        <Form ref={formRef} labelCol={longLabel} wrapperCol={longWrap} onFinish={d => sumbmitHandle(d, caseDetail as CaseSchema, topic as ServiceTopicSchema, refreshFn, hide)}>
          <Item name='status' noStyle><span /></Item>
          <Item name='contract_type' noStyle><span /></Item>
          <Item name='id' noStyle><span /></Item>
          <Row>
            <Col span={12}>
              <Item name='action_subject' label='仲裁地位' labelCol={shortLabel} wrapperCol={{ span: 17 }} rules={[{ required: true, message: '仲裁地位不能为空' }]}>
                <Select placeholder='请选中仲裁地位' onChange={e => {
                  formRef.current?.resetFields()
                  changeSubject(e, caseDetail, arbitrators, formRef, setContractList, setType)
                }}>
                  {partTypes.map(li => <Option key={li} value={li}>{li}</Option>)}
                </Select>
              </Item>
            </Col>
            <Col span={12}>
              <Item name='contractid' label='' labelCol={{ span: 0 }} colon={false} wrapperCol={{ span: 22 }} rules={[{ required: true, message: '名称不能为空' }]}>
                <Select placeholder='请选择名称/姓名' onChange={e => {changeContractId(e, contractList, formRef, type, allAddressList, setAddressList)}}>
                  {
                    contractList.map(li => {
                      return <Option key={li.id} value={li.id}>{li.name}</Option>
                    })
                  }
                </Select>
              </Item>
            </Col>
          </Row>
          <Item name='mobile' label='移动电话' rules={[{ required: true, message: '移动电话不能为空' }, { pattern: /^1\d{10}(,1\d{10})*$/g, message: '移动电话格式不正确，多个移动电话请以英文逗号隔开' }]}>
            <AutoComplete options={addressList} onSelect={(value: any, option: any) => changeAddress(formRef, option, caseid, topic as ServiceTopicSchema)}>
              <Input placeholder='请输入移动电话' />
            </AutoComplete>
          </Item>
          <Item name='email' label='邮箱' rules={[{ pattern: emailPattern, message: '邮箱格式不正确，多个邮箱请以英文逗号隔开' }]}>
            <Text format={fillEmpty} />
          </Item>
          <Item name='type' label='地址类型'>
            <Text format={fillEmpty} />
          </Item>
          <Item name='contract' label='收件人'>
            <Text format={fillEmpty} />
          </Item>
          <Item name='sms_content' label='送达短信'>
            <Text format={fillEmpty} />
          </Item>
          <Item name='email_content' label='送达邮件'>
            <Text format={fillEmpty} />
          </Item>
          <Item name='file' label='送达材料'>
            <Upload accept='.pdf' />
          </Item>
          <Item name='remark' label='备注'>
            <TextArea rows={3} placeholder='请输入备注' />
          </Item>
          {/* <Item name='islast_known_place' label='是否为最后一个为人所知的地址' labelCol={{}} valuePropName='checked'>
            <Switch checkedChildren='是' unCheckedChildren='否' />
          </Item> */}
        </Form>
      </Modal>
    </div>
  )
}

export default Main
